package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;

public class CapteurChoiceTask extends AsyncTask<String, Void, String>{
	
	public interface CapteurChoiceCallback {
		public void onCapteurTypeFound(String capteurType);
	}

	WeakReference<CapteurChoiceCallback> mCallback;
	
	public CapteurChoiceTask(CapteurChoiceCallback callback) {
		mCallback = new WeakReference<CapteurChoiceCallback>(callback);
	}

	@Override
	protected String doInBackground(String... urls) {

		try{
			//TODO : regarder quels timeout il faut mettre a une minute
			//String downloadUrl(String myurl, Integer connectTO, Integer readTO)
			String contentAsString = NetworkHelper.downloadUrl(urls[0], 60000, 60000);
			JSONObject root;
			root = new JSONObject(contentAsString);
			String codeString = root.getString("code");

			return codeString;
			
		} catch (IOException e){
			System.out.print("Unable to retrieve web page. URL may be invalid.");
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		
		
			if (mCallback.get() != null) {
				mCallback.get().onCapteurTypeFound(result);
			}
		}

}
